<template>
	<view class="uni-container">
		<uni-forms ref="form" :model="formData" validateTrigger="bind">
			<uni-forms-item name="category_id" label-width="100" label="商品类型" required>
				<!-- <uni-easyinput placeholder="分类 id，参考`opendb-mall-categories`表" v-model="formData.category_id"></uni-easyinput> -->
				<ljs-treeChoose-vue3 v-model="ljs_tree.treeData" :ids="ljs_tree.chooseIds" :props="ljs_tree.props"
					:keywordsFilter="true" :checkStrictly="true" @getChooseValue="ljs_treeGetChooseValue"
					:showAllLevels="false">
				</ljs-treeChoose-vue3>
			</uni-forms-item>
			<uni-forms-item name="goods_sn" label="货号" required>
				<uni-easyinput placeholder="请输入商品的唯一货号" v-model="formData.goods_sn" trim="both"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="name" label="名称" required>
				<uni-easyinput placeholder="请输入商品名称" v-model="formData.name" trim="both"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="master_id" label="非遗传承人" label-width="100" required>
				<view class="master-select-wrapper">
					<uni-easyinput v-model="masterInput" placeholder="请输入部分传承人姓名后选择" @input="onMasterInput"
						@focus="onMasterFocus" @blur="onMasterBlur" :disabled="false">
					</uni-easyinput>
					<!-- 下拉选项列表 -->
					<view v-if="showMasterDropdown && filteredMasters.length > 0" class="master-dropdown">
						<view v-for="master in filteredMasters" :key="master._id" class="master-item"
							@click="selectMaster(master)">
							<text class="master-name">{{ master.name }}--{{ master.direction }}</text>
						</view>
					</view>
					<!-- 无匹配结果提示 -->
					<view v-if="showMasterDropdown && masterInput && filteredMasters.length === 0" class="no-result">
						<text>未找到匹配的传承人</text>
					</view>
				</view>
			</uni-forms-item>
			<uni-forms-item name="price" label-width="100" label="商品实际价格" required>
				<uni-easyinput placeholder="请输入商品价格" type="number" v-model="formData.price" @blur="calculateDiscount"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="original_price" label-width="100" label="商品原始价格" required>
				<uni-easyinput placeholder="请输入原始价格" type="number" v-model="formData.original_price" @blur="calculateDiscount"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="discount" label-width="100" label="折扣">
				<uni-easyinput placeholder="自动计算折扣" type="digit" v-model="formData.discount" :disabled="true" readonly></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="producing_area" label-width="100" label="产地" required>
				<uni-data-picker 
					placeholder="请选择产地" 
					popup-title="请选择城市" 
					collection="opendb-city-china" 
					field="code as value, name as text" 
					orderby="value asc" 
					:step-searh="true" 
					self-field="code" 
					parent-field="parent_code"
					v-model="formData.producing_area.code"
					@change="onProducingAreaChange" 
					@nodeclick="onProducingAreaNodeClick">
				</uni-data-picker>
			</uni-forms-item>
			<uni-forms-item name="keywords" label="关键字">
				<uni-easyinput placeholder="请输入商品关键字，用逗号隔开" v-model="formData.keywords" trim="both"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="goods_desc" label-width="100" label="详细描述" required>
				<!-- <uni-easyinput placeholder="商品详细描述" v-model="formData.goods_desc" trim="both"></uni-easyinput> -->
				<view id="wangeditor-goods"></view>
			</uni-forms-item>
			<uni-forms-item name="goods_thumb" label="缩略图">
				<!-- <uni-easyinput placeholder="商品缩略图，用于在列表或搜索结果中预览显示" v-model="formData.goods_thumb"
					trim="both"></uni-easyinput> -->
				<button @click="chooseImage" size="mini">选择图片</button>
				<progress :percent="percent" show-info stroke-width="3" />
				<image v-if="formData.goods_thumb" :src="formData.goods_thumb" style="width: 100px; height: 100px;">
				</image>
			</uni-forms-item>
			<uni-forms-item name="goods_banner_imgs" label="轮播图" required>
				<button @click="chooseBannerImages" size="mini">选择轮播图</button>
				<progress :percent="bannerPercent" show-info stroke-width="3" />
				<view v-if="formData.goods_banner_imgs && formData.goods_banner_imgs.length > 0" class="banner-imgs">
					<view v-for="(img, index) in formData.goods_banner_imgs" :key="index" class="banner-img-item">
						<image :src="img" style="width: 80px; height: 80px; margin: 5px;"></image>
						<button @click="removeBannerImage(index)" size="mini" type="warn">删除</button>
					</view>
				</view>
			</uni-forms-item>
			<uni-forms-item name="sales_volume" label-width="100" label="销量">
				<uni-easyinput placeholder="请输入销量" type="number" v-model="formData.sales_volume"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="remain_count" label-width="100" label="库存数量" required>
				<uni-easyinput placeholder="请输入库存数量" type="number" v-model="formData.remain_count"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="comment_count" label-width="100" label="评论数">
				<uni-easyinput placeholder="请输入评论数" type="number" v-model="formData.comment_count"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="rating" label-width="100" label="商品评分">
				<uni-easyinput placeholder="请输入评分(0-5分)" type="digit" v-model="formData.rating"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="is_real" label-width="100" label="是否实物" required>
				<switch @change="binddata('is_real', $event.detail.value)" :checked="formData.is_real"></switch>
			</uni-forms-item>
<!-- 			<uni-forms-item name="month_sell_count" label="月销量" required>
				<uni-easyinput placeholder="月销量" type="number" v-model="formData.month_sell_count"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="total_sell_count" label="总销量" required>
				<uni-easyinput placeholder="总销量" type="number" v-model="formData.total_sell_count"></uni-easyinput>
			</uni-forms-item> -->
			<uni-forms-item name="is_on_sale" label-width="100" label="是否上架" required>
				<switch @change="binddata('is_on_sale', $event.detail.value)" :checked="formData.is_on_sale"></switch>
			</uni-forms-item>
			<uni-forms-item name="is_on_blockchain" label-width="100" label="是否上链" required>
				<switch @change="binddata('is_on_blockchain', $event.detail.value)" :checked="formData.is_on_blockchain"></switch>
			</uni-forms-item>
			<uni-forms-item name="is_best" label-width="100" label="是否精品">
				<switch @change="binddata('is_best', $event.detail.value)" :checked="formData.is_best"></switch>
			</uni-forms-item>
			<uni-forms-item name="is_hot" label-width="100" label="是否热销">
				<switch @change="binddata('is_hot', $event.detail.value)" :checked="formData.is_hot"></switch>
			</uni-forms-item>
			<uni-forms-item name="add_date" label="上架时间">
				<uni-datetime-picker return-type="timestamp" v-model="formData.add_date"></uni-datetime-picker>
			</uni-forms-item>
			<uni-forms-item name="last_modify_date" label="最近修改时间">
				<uni-datetime-picker return-type="timestamp" v-model="formData.last_modify_date"></uni-datetime-picker>
			</uni-forms-item>
			<uni-forms-item name="seller_note" label="商家备注">
				<uni-easyinput placeholder="商家备注，仅商家可见" v-model="formData.seller_note" trim="both"></uni-easyinput>
			</uni-forms-item>
			<view class="uni-button-group">
				<button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
				<navigator open-type="navigateBack" style="margin-left: 15px;">
					<button class="uni-button" style="width: 100px;">返回</button>
				</navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import {
	validator
} from '../../js_sdk/validator/opendb-mall-goods.js';

	import E from 'wangeditor';
	let goodsEditor = null

	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'opendb-mall-goods';
	const dbCollectionName2 = "opendb-mall-categories";
	const masterCollectionName = "intangible_master"; // 非遗传承人表名

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				result[key] = validator[key]
			}
		}
		return result
	}



	export default {
		data() {
			let formData = {
				"category_id": "",
				"goods_sn": "",
				"name": "",
				"master_id": "",
				"price": 0,
				"original_price": 0,
				"discount": null,
				"producing_area": {},
				"keywords": "",
				"goods_desc": "",
				"goods_thumb": "",
				"goods_banner_imgs": [],
				"sales_volume": 0,
				"remain_count": null,
				"comment_count": 0,
				"rating": null,
				"is_real": true,
				"is_on_sale": null,
				"is_on_blockchain":null,
				"is_best": null,
				"is_hot": null,
				"type":0,
				"add_date": null,
				"last_modify_date": null,
				"seller_note": ""
			}
			return {
				percent: 0, //图片上传进度条
				bannerPercent: 0, //轮播图上传进度条
				ljs_tree: {
					treeData: [],
					chooseIds: [], // 选择tree的id数据结果集合
					props: {
						label: 'name',
						id: '_id',
						children: 'children'
					},
				},
				formData,
				
				// 非遗传承人选择相关数据
				masterInput: '', // 传承人输入框的值
				masters: [], // 所有传承人数据
				filteredMasters: [], // 过滤后的传承人数据
				showMasterDropdown: false, // 是否显示下拉框
				masterSearchTimer: null, // 搜索防抖定时器

				formOptions: {},
				rules: {
					...getValidator(Object.keys(formData))
				}
			}
		},
		onLoad(e) {
			this.loadData()
			this.loadMasters()
			if (e.id) {
				const id = e.id
				this.formDataId = id
				this.getDetail(id)
			}
		},
		onReady() {
			this.initGoodsEditor()
			this.$refs.form.setRules(this.rules)
		},
		methods: {
			/**
			 * 初始化商品详情编辑器
			 */
			initGoodsEditor() {
				goodsEditor = new E('#wangeditor-goods')
				goodsEditor.config.zIndex = 0
				// 取消自动 focus
				goodsEditor.config.focus = false
				goodsEditor.config.onblur = function (newHtml) {
					console.log('onblur', newHtml) // 获取最新的 html 内容
				}
				goodsEditor.config.onfocus = function (newHtml) {
					console.log('onfocus', newHtml) // 获取最新的 html 内容
				}
				// 配置 onchange 回调函数
				const that = this
				goodsEditor.config.onchange = function (newHtml) {
					console.log("change 之后最新的 html", newHtml);
					that.formData.goods_desc = newHtml
				};
				// 配置触发 onchange 的时间频率，默认为 200ms
				goodsEditor.config.onchangeTimeout = 500; // 修改为 500ms

				// 本地上传图片
				goodsEditor.config.uploadImgMaxSize = 1 * 1024 * 1024 // 默认限制图片大小是 1M
				goodsEditor.config.uploadImgAccept = ['jpg', 'jpeg', 'png', 'gif', 'bmp',
					'webp'
				] // 默认['jpg', 'jpeg', 'png', 'gif', 'bmp']
				goodsEditor.config.customUploadImg = function (resultFiles, insertImgFn) {
					// resultFiles 是 input 中选中的文件列表
					// insertImgFn 是获取图片 url 后，插入到编辑器的方法
					resultFiles.forEach(async file => {
						let filePath = URL.createObjectURL(file)
						let cloudPath = file.name
						const result = await uniCloud.uploadFile({
							filePath,
							cloudPath
						});
						// 上传图片，返回结果，将图片插入到编辑器中
						// 腾讯云，支付宝云先使用getTempFileURL对fileID处理
						let temp = await uniCloud.getTempFileURL({
							fileList: [result.fileID]
						});
						temp.fileList.forEach((f) => {
							insertImgFn(f.tempFileURL)
						})
					})
				}
				goodsEditor.create()
			},

			/**
			 * 加载非遗传承人数据
			 */
			loadMasters() {
				db.collection(masterCollectionName)
					.field("_id,name,direction")
					.orderBy("name asc")
					.get()
					.then((res) => {
						this.masters = res.result.data
						console.log("masters", this.masters);
					}).catch((err) => {
						console.error('加载传承人数据失败:', err)
					})
			},

			/**
			 * 传承人输入框输入事件
			 */
			onMasterInput(value) {
				this.masterInput = value

				// 清除之前的定时器
				if (this.masterSearchTimer) {
					clearTimeout(this.masterSearchTimer)
				}

				// 防抖处理，延迟300ms执行搜索
				this.masterSearchTimer = setTimeout(() => {
					this.searchMasters(value)
				}, 300)
			},

			/**
			 * 传承人输入框获得焦点
			 */
			onMasterFocus() {
				if (this.masterInput) {
					this.searchMasters(this.masterInput)
				}
				this.showMasterDropdown = true
			},

			/**
			 * 传承人输入框失去焦点
			 */
			onMasterBlur() {
				// 延迟隐藏下拉框，让点击事件能够触发
				setTimeout(() => {
					this.showMasterDropdown = false
				}, 200)
			},

			/**
			 * 搜索传承人
			 */
			searchMasters(keyword) {
				if (!keyword || keyword.trim() === '') {
					this.filteredMasters = []
					return
				}

				const searchKeyword = keyword.toLowerCase().trim()
				this.filteredMasters = this.masters.filter(master => {
					return master.name.toLowerCase().includes(searchKeyword)
				}).slice(0, 10) // 最多显示10个结果
			},

			/**
			 * 选择传承人
			 */
			selectMaster(master) {
				this.masterInput = master.name
				this.formData.master_id = master._id
				this.showMasterDropdown = false
				console.log('选择的传承人:', master)
			},
			chooseImage() {
				const _self = this
				uniCloud.chooseAndUploadFile({
					type: 'image',
					count: 1,
					onChooseFile(res) {
						return Promise.all(res.tempFiles).then((fileList) => {
							let result = {
								tempFilePaths: []
							}
							result.tempFiles = fileList.map((fileItem, index) => {
								result.tempFilePaths.push(fileItem.path)
								// console.log(222222222222222,fileItem)
								return {
									path: fileItem.path,
									cloudPath: '' + Date.now() + index + '.' + fileItem.name.split(
										'.')[1], // 云端路径，这里随便生成了一个
									fileType: fileItem.fileType
								}
							})
							return result
						})
					},
					onUploadProgress(progressEvent) {
						console.log(progressEvent);
						_self.percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
					}
				}).then(async (res) => {
					// let temp = await uniCloud.getTempFileURL({
					// 	fileList: res.tempFiles.map((item) => item.url)
					// });
					// // console.log(111111111111,temp)
					// this.formData.goods_thumb = temp.fileList[0].tempFileURL
					// console.log(res)
					if (res && res.tempFiles && res.tempFiles.length > 0) {
						// 方式1：直接使用云存储返回的 URL（推荐）
						uni.showToast({
							icon: 'none',
							title: '上传成功',
							duration: 1500
						})
						this.formData.goods_thumb = res.tempFiles[0].url
						console.log("上传的图片", this.formData.goods_thumb)
					
						// 方式2：如果需要临时访问链接，使用文件ID
						// const tempUrlRes = await uniCloud.getTempFileURL({
						//     fileList: [res.tempFiles[0].fileID] // 注意：这里使用 fileID，不是 url
						// })
						// this.formData.goods_thumb = tempUrlRes.fileList[0].tempFileURL
					}
				}).catch(err => {
					console.error('上传过程出错:', err)
					uni.showToast({
						icon: 'none',
						title: '上传失败',
						duration: 1500
					})
				})
			},

			/**
			 * 选择轮播图
			 */
			chooseBannerImages() {
				const _self = this
				uniCloud.chooseAndUploadFile({
					type: 'image',
					count: 5, // 最多选择5张
					onChooseFile(res) {
						return Promise.all(res.tempFiles).then((fileList) => {
							let result = {
								tempFilePaths: []
							}
							result.tempFiles = fileList.map((fileItem, index) => {
								result.tempFilePaths.push(fileItem.path)
								return {
									path: fileItem.path,
									cloudPath: 'banner_' + Date.now() + index + '.' + fileItem.name.split('.')[1], // 云端路径，这里随便生成了一个
									fileType: fileItem.fileType
								}
							})
							return result
						})
					},
					onUploadProgress(progressEvent) {
						console.log('轮播图上传进度:', progressEvent);
						_self.bannerPercent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
					}
				}).then(async (res) => {
					if (res && res.tempFiles && res.tempFiles.length > 0) {
						// 参考缩略图的处理方式
						const urls = []
						for (let i = 0; i < res.tempFiles.length; i++) {
							const tempFile = res.tempFiles[i]
							if (tempFile.url) {
								urls.push(tempFile.url)
							}
						}
						
						// 将新上传的图片添加到现有轮播图数组中
						this.formData.goods_banner_imgs = [...(this.formData.goods_banner_imgs || []), ...urls]
						
						uni.showToast({
							icon: 'none',
							title: '轮播图上传成功',
							duration: 1500
						})
						console.log("上传的轮播图", this.formData.goods_banner_imgs)
					}
				}).catch(err => {
					console.error('轮播图上传失败:', err)
					uni.showToast({
						icon: 'none',
						title: '轮播图上传失败',
						duration: 1500
					})
				})
			},

			/**
			 * 删除轮播图
			 */
			removeBannerImage(index) {
				this.formData.goods_banner_imgs.splice(index, 1)
			},

			/**
			 * 产地选择改变事件
			 */
			onProducingAreaChange(e) {
				const value = e.detail.value
				let area = ''
				value.forEach(item => {
					area += item.text+"/"
				})
				this.formData.producing_area.text = area.substring(0, area.length - 1)
				console.log('产地选择改变:',value, this.formData.producing_area)
			},

			/**
			 * 产地节点点击事件
			 */
			onProducingAreaNodeClick(node) {
				console.log('产地节点点击:', node)
			},

			/**
			 * 计算折扣
			 */
			calculateDiscount() {
				const price = parseFloat(this.formData.price) || 0
				const originalPrice = parseFloat(this.formData.original_price) || 0
				
				if (originalPrice > 0 && price > 0) {
					// 计算折扣：实际价格 / 原始价格，保留2位小数
					const discount = (price/originalPrice).toFixed(2)
					this.formData.discount = parseFloat(discount)
				} else {
					this.formData.discount = null
				}
			},

			/**
			 * 绑定开关数据
			 */
			binddata(name, value) {
				this.formData[name] = value
			},
			/**
			 * 类别树展开
			 */
			loadData() {
				var that = this
				db.collection(dbCollectionName2)
					.field("sort,name,_id,parent_id")
					.orderBy("parent_id asc,sort asc")
					.get({
						getTree: true
					})
					.then((res) => {
						that.ljs_tree.treeData = res.result.data
						console.log("treeData", that.ljs_tree.treeData);
					}).catch((err) => {
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						})
					})
			},
			ljs_treeGetChooseValue(ids, items) {
				this.formData.category_id = ids[0]
				// console.log(ids,items)
				this.ljs_tree.chooseIds = ids;
			},
			/**
			 * 验证表单并提交
			 */
			submit() {
				uni.showLoading({
					mask: true
				})
				this.$refs.form.validate().then((res) => {
					return this.submitForm(res)
				}).catch(() => {}).finally(() => {
					uni.hideLoading()
				})
			},

			/**
			 * 提交表单
			 */
			submitForm(value) {
				// 使用 clientDB 提交数据
				return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
					uni.showToast({
						title: '修改成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					setTimeout(() => uni.navigateBack(), 500)
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			},

			/**
			 * 获取表单数据
			 * @param {Object} id
			 */
			getDetail(id) {
				uni.showLoading({
					mask: true
				})
				const goods = db.collection(dbCollectionName).where("_id=='" + id + "'").field(
					"category_id,goods_sn,name,master_id,price,original_price,discount,producing_area,keywords,goods_desc,goods_thumb,goods_banner_imgs,sales_volume,remain_count,comment_count,rating,is_real,is_on_sale,is_on_blockchain,is_best,is_hot,type,add_date,last_modify_date,seller_note"
				).getTemp()
				const master = db.collection(masterCollectionName).field(
					"_id,name"
				).getTemp()
				db.collection(goods, master).get().then((res) => {
					const data = res.result.data[0]
					// console.log(9991111, data)
					if (data) {
						const {
							master_id,
							...rest
						} = data
						this.formData = rest
						//设置传承人信息
						if (master_id && master_id.length > 0) {
							this.formData.master_id = master_id[0]._id
							this.masterInput = master_id[0].name
						}
						//设置父类别
						this.ljs_tree.chooseIds = [this.formData.category_id]
						//设置富文本编辑器内容
						if (goodsEditor && this.formData.goods_desc) {
							goodsEditor.txt.html(this.formData.goods_desc)
						}
					}
					
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			}
		}
	}
</script>
<style lang="scss">
	/* 非遗传承人选择样式 */
	.master-select-wrapper {
		position: relative;
		z-index: 98;
		/* 设置比商户稍低的层级 */
	}

	.master-dropdown {
		position: absolute;
		top: 100%;
		left: 0;
		right: 0;
		background-color: #fff;
		border: 1px solid #ddd;
		border-top: none;
		border-radius: 0 0 6px 6px;
		max-height: 200px;
		overflow-y: auto;
		z-index: 98;
		/* 设置比商户稍低的层级 */
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
	}

	.master-item {
		padding: 12px 16px;
		border-bottom: 1px solid #f5f5f5;
		cursor: pointer;
		transition: background-color 0.2s;

		&:hover {
			background-color: #f8f9fa;
		}

		&:last-child {
			border-bottom: none;
		}

		.master-name {
			display: block;
			font-size: 14px;
			color: #333;
			font-weight: 500;
			margin-bottom: 4px;
		}
	}

	.no-result {
		padding: 16px;
		text-align: center;
		color: #999;
		font-size: 14px;
	}

	/* 轮播图样式 */
	.banner-imgs {
		margin-top: 10px;
	}

	.banner-img-item {
		display: inline-block;
		position: relative;
		margin: 5px;
		border: 1px solid #ddd;
		border-radius: 4px;
		overflow: hidden;
		
		button {
			position: absolute;
			top: 2px;
			right: 2px;
			padding: 2px 6px;
			font-size: 12px;
			border-radius: 2px;
		}
	}
</style>